package library;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.util.Log;

public class GCMHttpConnect extends Thread{
	private static final String TAG = "HTTP";
	private String mString;
	private Context context;
	private ExPreferenceManager pm;
	private static final int MODE_ADD = 0;
	private static final int MODE_DELETE = 1;


	private int mode;


	public GCMHttpConnect(Context context, String url, int mode) {
		mString = url;				
		this.context = context;
		pm = new ExPreferenceManager(this.context);
		this.mode = mode;
	}


	@Override
	public void run() {
		download(mString);
	}


	public void download(String address) {
		StringBuilder jsonHtml = new StringBuilder();
		try{
			URL url = new URL(address);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setDefaultUseCaches(false);                                           
			conn.setDoInput(true);                        
			conn.setDoOutput(false);                      
			conn.setRequestMethod("GET");         

			if(conn != null){
				conn.setConnectTimeout(10000);
				conn.setUseCaches(false);
				if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
					BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
					for(;;){
						String line = br.readLine();
						if(line == null) break;
						jsonHtml.append(line);
					}
					br.close();
				}
				conn.disconnect();
				org.json.JSONObject result = new org.json.JSONObject(jsonHtml.toString());
				if(mode == MODE_ADD){

					boolean isSuccess = result.getBoolean("success");
					//	if(isSuccess){
					Log.d("GCM_Result", "SUCCESS!!!");
					pm.putItem("KeyRegister", "true");
					//	}

				}	else {
					
					boolean isSuccess = result.getBoolean("success");
					//	if(isSuccess){
					Log.d("GCM_Result", "SUCCESS!!!");
					pm.putItem("KeyRegister", "");
					//	}
	
				}

			}

		}catch(Exception e){
			Log.w(TAG, e.getMessage());
		}
	}
}
